﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace CrmTool
{
    public partial class Form1 : Form
    {
        private const int SW_SHOWNORMAL = 1;
        private const int SW_SHOWMINIMIZED = 2;
        private const int SW_SHOWMAXIMIZED = 3;

        [DllImport("user32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);

        [DllImport("user32.dll")]
        static extern bool SetForegroundWindow(IntPtr hWnd);

        private string CnnString = ConfigurationManager.ConnectionStrings["Db"].ConnectionString;
        private int KullaniciID = Convert.ToInt32(ConfigurationManager.AppSettings["KullaniciID"]);
        private string MakroPath = ConfigurationManager.AppSettings["MakroYol"];
        SqlConnection Conn;

        public Form1()
        {
            InitializeComponent();
            Conn = new SqlConnection(CnnString);
            this.Load += Form1_Load;
            this.FormClosed += Form1_FormClosed;
        }

        void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            Conn.Close();
        }

        void Form1_Load(object sender, EventArgs e)
        {
            Conn.Open();
        }

        private void Form1_Activated(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            MesajKontrol();
            timer1.Enabled = true;
        }

        private void MesajKontrol()
        {
            using (SqlCommand cmd = new SqlCommand("SELECT TOP (1) MakroEmirleri.Tip, MakroEmirleri.Parametreler, MakroTanimlari.MakroKodu FROM MakroEmirleri WITH (nolock) INNER JOIN MakroTanimlari ON MakroEmirleri.Tip = MakroTanimlari.Tip WHERE (MakroEmirleri.Calistirildi = 0) AND (MakroEmirleri.KullaniciID = @usr)", Conn))
            {
                cmd.Parameters.Add("@usr", SqlDbType.Int).Value = KullaniciID;
                SqlDataReader rd = cmd.ExecuteReader();
                if (rd.HasRows)
                {
                    rd.Read();

                    byte tip = rd.GetByte(0);
                    string param = rd.GetString(1);
                    string kod = rd.GetString(2);
                    MakroYaz(kod, param);
                    MikroAkifYap(tip);
                    UpdateMesajKontrol(tip);
                }
                rd.Close();
            }
        }

        private void UpdateMesajKontrol(byte tip)
        {
            using (SqlCommand cmd = new SqlCommand("UPDATE  MakroEmirleri  SET Calistirildi = 1 WHERE (KullaniciID = @usr) AND (Tip = @tip)", Conn))
            {
                cmd.Parameters.Add("@usr", SqlDbType.Int).Value = KullaniciID;
                cmd.Parameters.Add("@tip", SqlDbType.TinyInt).Value = tip;
                cmd.ExecuteNonQuery();
            }
        }

        private void MakroYaz(string makrokodu, string parametre)
        {
            string[] prm = parametre.Split(';');
            string kod = makrokodu;
            for (int i = 0; i < prm.Length; i++)
            {
                kod = kod.Replace("@" + (i + 1).ToString(), prm[i]);
            }
            File.WriteAllText(MakroPath, kod);
        }

        private void MikroAkifYap(byte tip)
        {
            foreach (Process item in Process.GetProcesses())
            {
                try
                {
                    if (item.MainModule.FileName.IndexOf("Mikro") > -1)
                    {
                        ShowWindowAsync(item.MainWindowHandle, SW_SHOWNORMAL);
                        SetForegroundWindow(item.MainWindowHandle);
                        SendKeys.Send(string.Format("^({0})", tip));
                        SetForegroundWindow(item.MainWindowHandle);
                        break;
                    }
                }
                catch (Exception)
                {
                }
            }
        }
    }
}
